// MenuBar.js
import React, { useState, useEffect, useRef } from "react";
import { NodeRegistrationDialog,  NodeFindDialog, ResultDialog}from'./DataSource';
import DataImportDialog from './DataImportDialog';
import { DataQueryDialog } from './DataQueryDialog';



const menuItems = [
  {
    label: '文件',
    children: [
      { label: '飞到首页', onClick: 'onFlyToHome' },
      { label: '切换图层', onClick: 'onToggleLayer' },
      {
        label: '更多操作',
        children: [
          { label: '操作1' },
          { label: '操作2' }
        ]
      }
    ]
  },
  {
    label: '视图',
    children: [
      { label: '消息视图' },
      { label: '日志视图' }
    ]
  },
  {
    label: '工具',
    children: [
      { label: '缩放至地球', onClick: 'onZoomToEarth' },
      { label: '数据入库',
        children: [
          { label: '二维数据入库',
            children: [
              { label: '单线程',
                children: [
                  { label: 'SHP矢量数据', onClick: 'onImportSHP' },
                  { label: 'JSON矢量数据' },
                  { label: 'JSON字符串' }
                ]
              },
              { label: '多线程' },
              { label: '分布式' }
            ]
          },
          { label: '三维数据入库' },
          { label: '入库管理' }
        ]
      }
    ]
  },
  {
     label: '查询节点', onClick: 'onNodeFind' 
  },
  {
    label: '数据查询',onClick: 'onDataQuery'
  },
  {
    label: '编码',
    children: [
      { label: '工具 1' },
      { label: '工具 2' }
    ]
  },
  {
    label: '版本',
    children: [
      { label: '版本信息' }
    ]
  },
  { label: 'SHP矢量数据', onClick: 'onImportSHP' }
];

const MenuItem = ({ item, onZoomToEarth, onNodeRegister, onNodeRemove, onNodeFind, onImportSHP, onDataQuery }) => {
  const [isOpen, setIsOpen] = useState(false);
  const menuRef = useRef(null);
  const hasChildren = item.children && item.children.length > 0;

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (menuRef.current && !menuRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };

    const handleMouseLeave = (event) => {
      if (menuRef.current && !menuRef.current.contains(event.relatedTarget)) {
        setIsOpen(false);
      }
    };

    const menuElement = menuRef.current;
    if (menuElement) {
      menuElement.addEventListener('mouseleave', handleMouseLeave);
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      if (menuElement) {
        menuElement.removeEventListener('mouseleave', handleMouseLeave);
      }
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  const handleClick = (e) => {
    e.stopPropagation();
    if (hasChildren) {
      setIsOpen(!isOpen);
    } else if (item.onClick) {
      if (item.onClick === 'onZoomToEarth') {
        onZoomToEarth();
      } else if (item.onClick === 'onNodeRegister') {
        onNodeRegister();
      } else if (item.onClick === 'onNodeRemove') {
        onNodeRemove();
      } else if (item.onClick === 'onNodeFind') {
        onNodeFind();
      } else if (item.onClick === 'onImportSHP') {
        onImportSHP(); 
      } else if (item.onClick === 'onDataQuery') {
        onDataQuery();
      }
    }
  };

  return (
    <li style={styles.menuItem} onClick={handleClick} ref={menuRef}>
      {item.label}
      {hasChildren && isOpen && (
        <ul style={styles.dropdownList}>
          {item.children.map((child, index) => (
            <MenuItem
              key={index}
              item={child}
              onZoomToEarth={onZoomToEarth}
              onNodeRegister={onNodeRegister}
              onNodeRemove={onNodeRemove}
              onNodeFind={onNodeFind}
              onImportSHP={onImportSHP}
              onDataQuery={onDataQuery}
            />
          ))}
        </ul>
      )}
    </li>
  );
};

const MenuBar = () => {
  const [isDialogOpen, setIsDialogOpen] = useState(false);

  const [isFindDialogOpen, setIsFindDialogOpen] = useState(false);
  const [isResultOpen, setIsResultOpen] = useState(false);
  const [isImportDialogOpen, setIsImportDialogOpen] = useState(false);
  const [resultData, setResultData] = useState([]);  // 存储查询结果数据
  const [zIndexCounter, setZIndexCounter] = useState(1000); // 初始化 z-index
  const [isDataQueryDialogOpen, setIsDataQueryDialogOpen] = useState(false);

  // 打开对话框时，增加 z-index
  const incrementZIndex = () => setZIndexCounter((prev) => prev + 10);
  const handleNodeRegister = () => {setIsDialogOpen(true);    incrementZIndex(); };

  const handleNodeFind = () => {
    setIsFindDialogOpen(false);// 隐藏查询
    handleNodeFindSubmit();  // 直接调用查询函数
  };
  const handleDialogClose = () => {setIsDialogOpen(false);};

  const handleFindDialogClose = () => {setIsFindDialogOpen(false);};
  const handleImportDialogClose = () => setIsImportDialogOpen(false);
  const handleImportSHP = () => setIsImportDialogOpen(true);
  const handleResultClose = () => setIsResultOpen(false);
  const handleDataQueryOpen = () => {
    setIsDataQueryDialogOpen(true);
  };
  const handleDataQueryClose = () => {
    setIsDataQueryDialogOpen(false);
  };
  

  const onZoomToEarth = () => {
    if (window.viewer && window.Cesium) {
      window.viewer.camera.flyTo({
        destination: window.Cesium.Cartesian3.fromDegrees(105, 40, 15000000.0), // 地球坐标
        duration: 0.5, // 动画持续时间，单位：秒
        easingFunction: window.Cesium.EasingFunction.QUAD_IN_OUT 
      });
    }
  };

  //注册节点提交函数
  const handleNodeSubmit = (formData) => {
    console.log('提交的数据:', formData);  // 添加调试输出
    
    const formBody = new URLSearchParams(formData).toString();
  
    fetch('/satxspace-gdm2/nodemanage/add', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded', // 使用表单编码类型
      },
      body: formBody, // 发送 URL 编码的表单数据
    })
      .then((response) => response.json())
      .then((data) => {
        console.log('成功:', data);
        setResultData(data);
        setIsResultOpen(true);
        handleDialogClose();
        
      })
      .catch((error) => {
        console.error('错误:', error);
      });
  };
  
  // 删除节点函数
  const handleNodeRemove = (indexLibraryName) => { 
    console.log(`准备注销节点：${indexLibraryName}`);
    // 这里可以调用后端API来注销节点
    fetch('/satxspace-gdm2/nodemanage/remove', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: new URLSearchParams({ index_library_name: indexLibraryName }).toString(),
    })
      .then((response) => response.json())
      .then((data) => {
        console.log('注销成功:', data);
        // 在注销成功后更新结果
        setResultData(prevData => prevData.filter(item => item.index_library_name !== indexLibraryName));
      })
      .catch((error) => {
        console.error('注销失败:', error);
      });
  };

  // 查询节点提交函数
  const handleNodeFindSubmit = () => {
    console.log('查询所有节点');

    const formBody = new URLSearchParams({ index_library_name: "" }).toString();  // 空字符串表示查询所有节点

    fetch('/satxspace-gdm2/nodemanage/find', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: formBody,  // 发送查询请求
    })
      .then((response) => response.json())
      .then((data) => {
        console.log('查询结果:', data);
        setResultData(data.data.item);  // 存储查询结果数据
        setIsResultOpen(true);  // 打开结果对话框
      })
      .catch((error) => {
        console.error('错误:', error);
        setResultData([]);  // 请求失败时清空结果数据
        setIsResultOpen(true);  // 打开结果对话框，显示错误信息
      });
  };

    // 提交数据查询
    const handleDataQuerySubmit = (indexLibraryName, bigTableNames, geometryOrGrid) => {
      console.log("查询数据源:", indexLibraryName, "表名:", bigTableNames, "几何范围:", geometryOrGrid);
  
      const formData = new URLSearchParams({
        index_library_name: indexLibraryName,
        big_table_names: bigTableNames,
        geometry_or_grid: geometryOrGrid, // 传入绘制的GeoJSON
        page_num: 1,
        page_size: 10000,
      }).toString();
  
      fetch("satxspace-gdm2/data/search/grid", {
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        body: formData,
      })
        .then((response) => response.json())
        .then((data) => {
          console.log("查询结果:", data);
          alert("查询成功！");
          handleDataQueryClose();
        })
        .catch((error) => {
          console.error("错误:", error);
          alert("查询失败！");
        });
    };

  
  
  return (
    <nav style={styles.menuBar}>
      <ul style={styles.menuList}>
        {menuItems.map((item, index) => (
          <MenuItem
            key={index}
            item={item}
            onZoomToEarth={onZoomToEarth}
            onNodeRegister={handleNodeRegister}
            onNodeRemove={handleNodeRemove}
            onNodeFind={handleNodeFind}
            onImportSHP={handleImportSHP}
            onDataQuery={handleDataQueryOpen}
            
          />
        ))}
      </ul>
      <NodeRegistrationDialog isOpen={isDialogOpen} onClose={handleDialogClose} onSubmit={handleNodeSubmit}zIndex={zIndexCounter}   />
      <NodeFindDialog isOpen={isFindDialogOpen} onClose={handleFindDialogClose} onSubmit={handleNodeFindSubmit} />
      <DataImportDialog isOpen={isImportDialogOpen} onClose={handleImportDialogClose} />
      <ResultDialog isOpen={isResultOpen} onClose={handleResultClose} result={resultData} onNodeRemove={handleNodeRemove} onNodeRegister={handleNodeRegister} />
      <DataQueryDialog isOpen={isDataQueryDialogOpen} onClose={handleDataQueryClose} onSubmit={handleDataQuerySubmit} />
      
    </nav>
  );
};

const styles = {
  menuBar: {
    position: "absolute",
    top: 10,
    left: 10,
    zIndex: 1000,
    backgroundColor: "rgba(255, 255, 255, 0.7)",
    padding: "10px",
    borderRadius: "5px",
    display: "flex",
    flexDirection: "row",
    gap: "10px",
    alignItems: "center",
  },
  menuList: {
    listStyle: "none",
    padding: 0,
    margin: 0,
    display: "flex",
    gap: "10px",
  },
  menuItem: {
    position: "relative",
    cursor: "pointer",
    padding: "5px 10px",
    backgroundColor: "rgba(255, 255, 255, 0.7)",
    borderRadius: "3px",
    '&:hover': {
      backgroundColor: "rgba(255, 255, 255, 0.9)"
    }
  },
  dropdownList: {
    position: "absolute",
    left: 0,
    top: "100%",
    backgroundColor: "white",
    border: "1px solid #ccc",
    borderRadius: "5px",
    padding: "5px 0",
    listStyle: "none",
    width: "120px",
    zIndex: 10,
    '& ul': {
      left: "100%",
      top: 0,
      marginLeft: "5px"
    }
  }
};

export default MenuBar;